package com.cqhfan.chatroom.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.cqhfan.chatroom.domain.dto.WebSocketMessageDTO;
import com.cqhfan.chatroom.domain.po.ChatGroupUser;
import com.cqhfan.chatroom.handler.UserConnectionSession;
import com.cqhfan.chatroom.mapper.ChatGroupUserMapper;
import com.cqhfan.chatroom.service.IChatGroupUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqhfan.common.constants.RedisConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 群聊用户 服务实现类
 * </p>
 *
 * @author 眭传洪
 * @since 2024-11-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatGroupUserServiceImpl extends ServiceImpl<ChatGroupUserMapper, ChatGroupUser> implements IChatGroupUserService {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void noticeChatGroupCreateMsg(String msg) {
        WebSocketMessageDTO msgDTO = JSONUtil.toBean(msg, WebSocketMessageDTO.class);
        Long groupId = msgDTO.getGroupId();

        // 查询redis中群的人
        String key = RedisConstants.GROUP_MEMBERS_KEY_PREFIX + groupId;
        Set<String> cacheGroupUserIds = stringRedisTemplate.opsForSet().members(key);
        if (CollUtil.isEmpty(cacheGroupUserIds)) {
            return;
        }
        Set<Long> userIds = cacheGroupUserIds.stream().map(Long::valueOf).collect(Collectors.toSet());

        // 拿到本机下所有的人
        Set<Long> currentNodeUserIds = UserConnectionSession.getConnectionUserIds();

        // 求出交集并发送即时消息
        Collection<Long> currentNodeGroupUserIds = CollUtil.intersection(userIds, currentNodeUserIds);
        currentNodeGroupUserIds.remove(msgDTO.getSenderId());
        log.info("群id {} 下的本机用户{}", groupId, currentNodeGroupUserIds);

        // 发送消息
        for (Long userId : currentNodeGroupUserIds) {
            WebSocketSession session = UserConnectionSession.getSessionByUserId(userId);
            if (session == null || !session.isOpen()) {
                continue;
            }
            try {
                session.sendMessage(new TextMessage(msg));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
